<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-4-19
 * Time: 下午1:43
 * 取消订单手续费
 */
//defined('IN_PFT') or exit('No permission resources.');
include("/var/www/html/new/com.inc.php");
include("/var/www/html/new/d/class/SoapInit.class.php");


define('LOG_REQUEST', '/var/www/html/new/d/logs/refund/req_'.date('ymd').'.txt');
define('LOG_NAME', '/var/www/html/new/d/logs/refund/err_'.date('ymd').'.txt');
define('LOG_NAME_OK', '/var/www/html/new/d/logs/refund/ok_'.date('ymd').'.txt');
define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);

LogRefund(json_encode($_REQUEST), LOG_REQUEST);

if (!defined('MANUAL')) {
    $comp = md5(md5($_GET['ordernum']).md5(strrev($_GET['ordernum'])));
    if (empty($_GET['auth']) || $_GET['auth']!=$comp) {
        LogRefund('身份验证失败',LOG_NAME);
        Response("身份验证失败");
    }
}

if (empty($_REQUEST['ordernum'])) {
    LogRefund('订单号不能为空',LOG_NAME);
    Response('订单号不能为空');
}



/**
 * 计算订单取消费用，是根据票数退款哦~
 *
 * @author GuangPeng Chen
 * @param Int $tid      门票ID
 * @param Int $price    价格（单位分）
 * @param string $beginTime     订单游玩时间
 * @return array|bool|int       成功返回退票手续费，金额分
 */
function count_cost_fee( $tid, $price, $beginTime)
{
    $play_date = strtotime( $beginTime . ' 00:00:00');
    $today     = strtotime(date('Y-m-d 00:00:00'));
    $day_diff  = ($play_date - $today) / 86400;//距离游玩时间的天数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额

    //使用cancel_cost字段收取手续费的供应商，目前（2014年12月19日）只有云顶
//    $use_cancel_cost = array(
//        7133,7134,7135,7136,
//    );
    //reb_type
    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket"
        . " WHERE id=$tid LIMIT 1";
    $GLOBALS['le']->query($sql);
    $total_fee    = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row    = $GLOBALS['le']->fetch_assoc()) {
        //in_array($row['apply_did'], $use_cancel_cost) &&
        if ($row['cancel_cost']) {
//            if (!$row['cancel_cost']) continue;
            $cancel_cost = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                //按百分比收取手续费
                $total_fee += ($row['reb'] * $price) / 100;
            }
        }
    }
    //阶梯扣费
//    `cancel_cost` varchar(2000) NOT NULL, /*取消费用 二维数组 array(array('c_type'=>类型 0 固定金额 1 百分比,'c_days'=>游玩前分钟,'c_cost'=>费用值))*/

    if (isset($cancel_cost) && !empty($cancel_cost)) {
        //取消费用一维数组 array('提前天数'=>'百分比')
        $cancel_cost_arr = json_encode($cancel_cost, true);
//        foreach ($cancel_cost_arr as $cancel) {
//
//        }
        $day_arr         = array_keys($cancel_cost_arr);
        sort($day_arr);
        $min_day         = min($day_arr);
        $max_day         = max($day_arr);
        if ($day_diff <= $min_day) {
            $fee = $cancel_cost_arr[$min_day];
        }
        elseif ($day_diff >= $max_day) {
            $fee = 0;
        } else {
            foreach ($day_arr as $key=>$val) {
                if ($day_diff >= $val && $day_diff <= $day_arr[$key+1]) {
                    $fee = $day_arr[$key+1];
                    break;
                }
            }
        }
        $total_fee += ($fee * $price) / 100  ;
    }
    return $total_fee;
}



function LogRefund($txt,$file='/var/www/html/new/d/logs/refund_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function Response( $msg, $status = "fail") {
    $json = '{"status":"'.$status.'", "msg":"'.$msg.'"}';
    exit($json);
}

$ordernum = trim($_REQUEST['ordernum']);//13
$soap = SoapInit::GetSoapInside();
$xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
    $ordernum, "", "", "", "", "", "", "1", "0", "1", "0", "0",
    "", "0", "", "0", "", "", "", "0", "0");
//echo $xml;Response;
$order_arr = simplexml_load_string($xml);
//print_r($order_arr);Response;
if (!count($order_arr)) {
    LogRefund("[{$ordernum}]|订单号不能为空",LOG_NAME);
    Response("订单不存在。");
}
$aid    = (int)$order_arr->Rec->UUaid;
$sellid = (int)$order_arr->Rec->UUsellid;

//TODO::判断订单状态，未使用，已支付
if ( $order_arr->Rec->UUpaystatus !=1
    || ($order_arr->Rec->UUpmode !=0 && $order_arr->Rec->UUpmode!=2)) {
    LogRefund(
        "[{$ordernum}]|只有已支付未使用并且是使用账户余额OR授信方可退款"//新加银联 15-06-02
        ."|UUstatus={$order_arr->Rec->UUstatus}，UUpaystatus={$order_arr->Rec->UUpaystatus}"
        ."，UUpmode={$order_arr->Rec->UUpmode}",LOG_NAME);
    Response("只有已支付未使用并且是使用账户余额OR授信方可退款。" . $order_arr->Rec->UUpmode);
}
//$order_type = 0;
//TODO::判断订单类型
if ($order_arr->Rec->UUpack_order==1) {
    //套票
    $main_order = (string)$order_arr->Rec->UUordernum;
}
elseif ($order_arr->Rec->UUconcat_id>0
    && (string)$order_arr->Rec->UUconcat_id!=(string)$order_arr->Rec->UUordernum)
{
    //联票订单
    $main_order = (string)$order_arr->Rec->UUconcat_id;
}
else {
    //普通订单
}

//退票数，0表示取消订单
$FeeCost   = 0;//取消费用
$TotalFee  = 0;

//取消订单
$TotalFee  = (int)$order_arr->Rec->UUtprice * (int)$order_arr->Rec->UUtnum;
//一张票的取消费用
$FeeCost   = count_cost_fee(
    (int)$order_arr->Rec->UUtid,
    (int)$order_arr->Rec->UUtprice,
    (string)$order_arr->UUbegintime
);
//TODO::获取这个订单的票数
$sql = "SELECT pre_num FROM pft_order_num_modify WHERE orderid='$ordernum' ORDER BY id ASC limit 1";
$GLOBALS['le']->query($sql);
$GLOBALS['le']->fetch_assoc();
$preNum   = $GLOBALS['le']->f('pre_num');
$FeeCost  = $preNum ? $preNum * $FeeCost : (int)$order_arr->Rec->UUtnum * $FeeCost;//所有票数的取消费用
$TotalFee_tmp = $TotalFee - $FeeCost;//原订单总金额-取消费用
$TotalFee = $TotalFee_tmp < 0 ? 0 : $TotalFee_tmp;


$TopAid = $aid;



if ( $FeeCost>0 ) {
    $add = 0;
    $cut = 1;
    //转分销的订单
    if ($order_arr->UUaids_money!=0) {
//        $aid_list   = explode(',', $order_arr->UUaids);
//        $TopAid     = array_shift($aid_list);
//        $LastAid    = array_pop($aid_list);
        $aids_money = unserialize((string)$order_arr->UUaids_money);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
//            if ($fid==$TopAid) continue;
            if($row[1]==0){//信用额度
                $dmode = 1;
                $soap->PFT_Member_Fund_Modify($fid,$opID,$FeeCost,0,$dmode,$row[4],14,2,$ordernum, '退票手续费');
            }else{//资金
                $dmode = 0;
                $soap->PFT_Member_Fund_Modify($fid,$opID,$FeeCost, intval(! $row[2]),$dmode,NULL,14,0,$ordernum,'退票手续费');
            }
        }
        //购买者扣钱
        $soap->PFT_Member_Fund_Modify((int)$order_arr->UUmid,$opID,$FeeCost,1,(int)$order_arr->UUpmode,(int)$order_arr->UUaid,14,0,$ordernum,'退票手续费');
    }
    else {
        //直销的订单
        $pay_type = (int)$order_arr->UUpmode;
        if ($order_arr->UUpmode==0) {
            //供应商加钱
            $res = $soap->PFT_Member_Fund_Modify((int)$order_arr->UUaid, 0, $FeeCost, ACTION_MONEY_ADD, 0, null, 14, 0, $ordernum, '退票手续费');
            $res = $soap->PFT_Member_Fund_Modify((int)$order_arr->UUmid, 0, $FeeCost, ACTION_MONEY_CUT,0,null, 14, 0,$ordernum, '退票手续费');
        } elseif ($order_arr->UUpmode==2) {
            //分销商扣授信额度
            $res = $soap->PFT_Member_Fund_Modify((int)$order_arr->UUmid, 0, $FeeCost, ACTION_MONEY_CUT, 1,(int)$order_arr->UUaid, 14, 2,$ordernum, '退票手续费');
        }

    }
}
LogRefund("[{$ordernum}]{$subject}成功",LOG_NAME_OK);
Response("success", "ok");